<template>
    <div class="subtitle-editor-container">
        <n-card class="subtitle-card">
            <template #header>
                <div class="card-header">
                    <h1>字幕编辑器</h1>
                    <div class="header-actions">
                        <n-button @click="saveSubtitles" type="primary">
                            <template #icon><n-icon>
                                    <SaveOutline />
                                </n-icon></template>
                            保存字幕
                        </n-button>
                        <n-button @click="importSubtitles">
                            <template #icon><n-icon>
                                    <CloudUploadOutline />
                                </n-icon></template>
                            导入字幕
                        </n-button>
                        <n-button @click="exportSubtitles">
                            <template #icon><n-icon>
                                    <CloudDownloadOutline />
                                </n-icon></template>
                            导出字幕
                        </n-button>
                        <n-button @click="goBack">
                            <template #icon><n-icon>
                                    <ArrowBackOutline />
                                </n-icon></template>
                            返回
                        </n-button>
                    </div>
                </div>
            </template>

            <div class="subtitle-content">
                <div class="toolbar">
                    <n-button-group>
                        <n-button @click="play">
                            <template #icon><n-icon>
                                    <PlayOutline />
                                </n-icon></template>
                            播放
                        </n-button>
                        <n-button @click="pause">
                            <template #icon><n-icon>
                                    <PauseOutline />
                                </n-icon></template>
                            暂停
                        </n-button>
                        <n-button @click="stop">
                            <template #icon><n-icon>
                                    <StopOutline />
                                </n-icon></template>
                            停止
                        </n-button>
                    </n-button-group>

                    <n-space>
                        <span class="time-display">{{ formatTime(currentTime) }}</span>
                        <span class="separator">/</span>
                        <span class="time-display">{{ formatTime(totalDuration) }}</span>
                    </n-space>

                    <n-button @click="addSubtitle">
                        <template #icon><n-icon>
                                <AddOutline />
                            </n-icon></template>
                        添加字幕
                    </n-button>
                </div>

                <div class="video-preview">
                    <div class="video-container">
                        <img :src="previewImage" alt="视频预览" class="video-frame" />

                        <!-- 字幕预览 -->
                        <div class="subtitle-preview" v-if="currentSubtitle">
                            <div class="subtitle-text" :style="{
                                fontFamily: currentSubtitle.style.fontFamily,
                                fontSize: currentSubtitle.style.fontSize + 'px',
                                color: currentSubtitle.style.color,
                                textShadow: currentSubtitle.style.shadow ? '1px 1px 2px rgba(0,0,0,0.8)' : 'none',
                                backgroundColor: currentSubtitle.style.background || 'transparent',
                                padding: currentSubtitle.style.background ? '4px 8px' : '0',
                                borderRadius: currentSubtitle.style.background ? '4px' : '0',
                                textAlign: currentSubtitle.style.alignment
                            }">
                                {{ currentSubtitle.text }}
                            </div>
                        </div>

                        <!-- 播放进度条 -->
                        <div class="video-progress">
                            <div class="progress-bar">
                                <div class="progress-fill"
                                    :style="{ width: `${(currentTime / totalDuration) * 100}%` }"></div>

                                <!-- 字幕标记 -->
                                <div v-for="subtitle in subtitles" :key="subtitle.id" class="subtitle-marker"
                                    :style="{ left: `${(subtitle.startTime / totalDuration) * 100}%`, width: `${((subtitle.endTime - subtitle.startTime) / totalDuration) * 100}%` }"
                                    :class="{ 'active': currentSubtitle && currentSubtitle.id === subtitle.id }"
                                    @click="selectSubtitle(subtitle)"></div>

                                <!-- 播放头 -->
                                <div class="playhead" :style="{ left: `${(currentTime / totalDuration) * 100}%` }">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="subtitle-list">
                    <div class="list-header">
                        <div class="header-time">时间</div>
                        <div class="header-text">文本</div>
                        <div class="header-actions">操作</div>
                    </div>

                    <div class="list-body">
                        <div v-for="subtitle in subtitles" :key="subtitle.id" class="subtitle-item"
                            :class="{ 'selected': selectedSubtitle && selectedSubtitle.id === subtitle.id }"
                            @click="selectSubtitle(subtitle)">
                            <div class="item-time">
                                {{ formatTime(subtitle.startTime) }} - {{ formatTime(subtitle.endTime) }}
                            </div>
                            <div class="item-text">{{ subtitle.text }}</div>
                            <div class="item-actions">
                                <n-button-group size="small">
                                    <n-button @click.stop="editSubtitle(subtitle)">
                                        <template #icon><n-icon>
                                                <PencilOutline />
                                            </n-icon></template>
                                    </n-button>
                                    <n-button @click.stop="deleteSubtitle(subtitle.id)">
                                        <template #icon><n-icon>
                                                <TrashOutline />
                                            </n-icon></template>
                                    </n-button>
                                </n-button-group>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="subtitle-editor" v-if="selectedSubtitle">
                    <n-tabs type="line" animated>
                        <n-tab-pane name="content" tab="内容">
                            <n-form :model="subtitleForm" label-placement="left" label-width="100">
                                <n-form-item label="开始时间" path="startTime">
                                    <n-input-number v-model:value="subtitleForm.startTime" :min="0" :max="totalDuration"
                                        :step="100" />
                                </n-form-item>

                                <n-form-item label="结束时间" path="endTime">
                                    <n-input-number v-model:value="subtitleForm.endTime" :min="0" :max="totalDuration"
                                        :step="100" />
                                </n-form-item>

                                <n-form-item label="字幕文本" path="text">
                                    <n-input v-model:value="subtitleForm.text" type="textarea"
                                        :autosize="{ minRows: 2, maxRows: 5 }" placeholder="输入字幕文本..." />
                                </n-form-item>

                                <n-space justify="end">
                                    <n-button @click="updateSubtitle" type="primary">更新字幕</n-button>
                                </n-space>
                            </n-form>
                        </n-tab-pane>

                        <n-tab-pane name="style" tab="样式">
                            <n-form :model="subtitleForm.style" label-placement="left" label-width="100">
                                <n-form-item label="字体" path="fontFamily">
                                    <n-select v-model:value="subtitleForm.style.fontFamily" :options="fontOptions" />
                                </n-form-item>

                                <n-form-item label="字号" path="fontSize">
                                    <n-input-number v-model:value="subtitleForm.style.fontSize" :min="12" :max="72" />
                                </n-form-item>

                                <n-form-item label="颜色" path="color">
                                    <n-color-picker v-model:value="subtitleForm.style.color" />
                                </n-form-item>

                                <n-form-item label="对齐方式" path="alignment">
                                    <n-select v-model:value="subtitleForm.style.alignment"
                                        :options="alignmentOptions" />
                                </n-form-item>

                                <n-form-item label="文字阴影">
                                    <n-switch v-model:value="subtitleForm.style.shadow" />
                                </n-form-item>

                                <n-form-item label="背景色">
                                    <n-color-picker v-model:value="subtitleForm.style.background" :show-alpha="true" />
                                </n-form-item>

                                <n-space justify="end">
                                    <n-button @click="updateSubtitle" type="primary">更新样式</n-button>
                                </n-space>
                            </n-form>
                        </n-tab-pane>

                        <n-tab-pane name="animation" tab="动画">
                            <n-form :model="subtitleForm.animation" label-placement="left" label-width="100">
                                <n-form-item label="入场动画" path="enter">
                                    <n-select v-model:value="subtitleForm.animation.enter"
                                        :options="animationOptions" />
                                </n-form-item>

                                <n-form-item label="入场时长" path="enterDuration">
                                    <n-input-number v-model:value="subtitleForm.animation.enterDuration" :min="0"
                                        :max="2000" :step="100" />
                                </n-form-item>

                                <n-form-item label="出场动画" path="exit">
                                    <n-select v-model:value="subtitleForm.animation.exit" :options="animationOptions" />
                                </n-form-item>

                                <n-form-item label="出场时长" path="exitDuration">
                                    <n-input-number v-model:value="subtitleForm.animation.exitDuration" :min="0"
                                        :max="2000" :step="100" />
                                </n-form-item>

                                <n-space justify="end">
                                    <n-button @click="updateSubtitle" type="primary">更新动画</n-button>
                                </n-space>
                            </n-form>
                        </n-tab-pane>
                    </n-tabs>
                </div>
            </div>
        </n-card>

        <n-modal v-model:show="importModalVisible" title="导入字幕" preset="card" style="width: 600px;">
            <n-form>
                <n-form-item label="字幕文件">
                    <n-upload action="http://dummy-upload-url" :default-upload="false" @change="handleFileChange">
                        <n-button>选择文件</n-button>
                    </n-upload>
                    <div class="upload-tip">支持SRT、VTT格式</div>
                </n-form-item>

                <n-form-item label="字符编码">
                    <n-select v-model:value="importEncoding" :options="encodingOptions" />
                </n-form-item>
            </n-form>

            <template #footer>
                <n-space justify="end">
                    <n-button @click="importModalVisible = false">取消</n-button>
                    <n-button type="primary" @click="confirmImport" :disabled="!importFile">导入</n-button>
                </n-space>
            </template>
        </n-modal>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'
import {
    NCard,
    NButton,
    NButtonGroup,
    NIcon,
    NSpace,
    NInput,
    NInputNumber,
    NForm,
    NFormItem,
    NTabs,
    NTabPane,
    NSelect,
    NColorPicker,
    NSwitch,
    NModal,
    NUpload
} from 'naive-ui'
import {
    SaveOutline,
    ArrowBackOutline,
    PlayOutline,
    PauseOutline,
    StopOutline,
    AddOutline,
    CloudUploadOutline,
    CloudDownloadOutline,
    PencilOutline,
    TrashOutline
} from '@vicons/ionicons5'

const router = useRouter()
const message = useMessage()

// 视频数据
const totalDuration = ref(60000) // 60秒
const currentTime = ref(0)
const previewImage = ref('https://picsum.photos/id/1043/800/450') // 示例预览图片

// 选中的字幕
const selectedSubtitle = ref<any>(null)
const currentSubtitle = computed(() => {
    // 找到当前时间点应该显示的字幕
    return subtitles.value.find(subtitle =>
        currentTime.value >= subtitle.startTime &&
        currentTime.value <= subtitle.endTime
    )
})

// 导入相关
const importModalVisible = ref(false)
const importFile = ref<File | null>(null)
const importEncoding = ref('utf-8')

// 编码选项
const encodingOptions = [
    { label: 'UTF-8', value: 'utf-8' },
    { label: 'GB2312', value: 'gb2312' },
    { label: 'Big5', value: 'big5' },
    { label: 'UTF-16', value: 'utf-16' }
]

// 字幕列表
const subtitles = ref([
    {
        id: '1',
        startTime: 2000,
        endTime: 5000,
        text: '欢迎使用皮影快闪',
        style: {
            fontFamily: 'Microsoft YaHei',
            fontSize: 24,
            color: '#FFFFFF',
            alignment: 'center',
            shadow: true,
            background: null
        },
        animation: {
            enter: 'fade',
            enterDuration: 500,
            exit: 'fade',
            exitDuration: 500
        }
    },
    {
        id: '2',
        startTime: 7000,
        endTime: 10000,
        text: '这是一个强大的动画制作工具',
        style: {
            fontFamily: 'Microsoft YaHei',
            fontSize: 24,
            color: '#FFFFFF',
            alignment: 'center',
            shadow: true,
            background: null
        },
        animation: {
            enter: 'slide-up',
            enterDuration: 800,
            exit: 'fade',
            exitDuration: 500
        }
    },
    {
        id: '3',
        startTime: 12000,
        endTime: 16000,
        text: '你可以轻松添加和编辑字幕',
        style: {
            fontFamily: 'Microsoft YaHei',
            fontSize: 26,
            color: '#FFFF00',
            alignment: 'center',
            shadow: true,
            background: 'rgba(0, 0, 0, 0.5)'
        },
        animation: {
            enter: 'scale',
            enterDuration: 600,
            exit: 'scale',
            exitDuration: 600
        }
    }
])

// 字幕表单
const subtitleForm = reactive({
    id: '',
    startTime: 0,
    endTime: 0,
    text: '',
    style: {
        fontFamily: 'Microsoft YaHei',
        fontSize: 24,
        color: '#FFFFFF',
        alignment: 'center',
        shadow: true,
        background: null
    },
    animation: {
        enter: 'fade',
        enterDuration: 500,
        exit: 'fade',
        exitDuration: 500
    }
})

// 字体选项
const fontOptions = [
    { label: '微软雅黑', value: 'Microsoft YaHei' },
    { label: '宋体', value: 'SimSun' },
    { label: '黑体', value: 'SimHei' },
    { label: '楷体', value: 'KaiTi' },
    { label: 'Arial', value: 'Arial' },
    { label: 'Verdana', value: 'Verdana' },
    { label: 'Georgia', value: 'Georgia' }
]

// 对齐选项
const alignmentOptions = [
    { label: '左对齐', value: 'left' },
    { label: '居中', value: 'center' },
    { label: '右对齐', value: 'right' }
]

// 动画选项
const animationOptions = [
    { label: '淡入淡出', value: 'fade' },
    { label: '从下滑入', value: 'slide-up' },
    { label: '从上滑入', value: 'slide-down' },
    { label: '从左滑入', value: 'slide-left' },
    { label: '从右滑入', value: 'slide-right' },
    { label: '缩放', value: 'scale' },
    { label: '无', value: 'none' }
]

// 格式化时间
const formatTime = (ms: number) => {
    const totalSeconds = Math.floor(ms / 1000)
    const minutes = Math.floor(totalSeconds / 60)
    const seconds = totalSeconds % 60
    const milliseconds = Math.floor((ms % 1000) / 10)

    return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}.${milliseconds.toString().padStart(2, '0')}`
}

// 选择字幕
const selectSubtitle = (subtitle: any) => {
    selectedSubtitle.value = subtitle

    // 更新表单数据
    subtitleForm.id = subtitle.id
    subtitleForm.startTime = subtitle.startTime
    subtitleForm.endTime = subtitle.endTime
    subtitleForm.text = subtitle.text
    subtitleForm.style = { ...subtitle.style }
    subtitleForm.animation = { ...subtitle.animation }

    // 将时间轴调整到字幕开始位置
    currentTime.value = subtitle.startTime

    message.success(`已选择字幕: ID ${subtitle.id}`)
}

// 添加字幕
const addSubtitle = () => {
    const newId = (parseInt(subtitles.value[subtitles.value.length - 1]?.id || '0') + 1).toString()

    const newSubtitle = {
        id: newId,
        startTime: currentTime.value,
        endTime: currentTime.value + 3000, // 默认3秒
        text: '新字幕',
        style: {
            fontFamily: 'Microsoft YaHei',
            fontSize: 24,
            color: '#FFFFFF',
            alignment: 'center',
            shadow: true,
            background: null
        },
        animation: {
            enter: 'fade',
            enterDuration: 500,
            exit: 'fade',
            exitDuration: 500
        }
    }

    subtitles.value.push(newSubtitle)
    selectSubtitle(newSubtitle)

    message.success('已添加新字幕')
}

// 编辑字幕
const editSubtitle = (subtitle: any) => {
    selectSubtitle(subtitle)
}

// 更新字幕
const updateSubtitle = () => {
    if (!selectedSubtitle.value) return

    const index = subtitles.value.findIndex(subtitle => subtitle.id === subtitleForm.id)
    if (index === -1) return

    // 更新字幕数据
    subtitles.value[index] = {
        ...subtitleForm,
        id: subtitleForm.id
    }

    message.success('字幕已更新')
}

// 删除字幕
const deleteSubtitle = (id: string) => {
    const index = subtitles.value.findIndex(subtitle => subtitle.id === id)
    if (index === -1) return

    subtitles.value.splice(index, 1)

    // 如果删除的是当前选中的字幕，清除选中状态
    if (selectedSubtitle.value && selectedSubtitle.value.id === id) {
        selectedSubtitle.value = null
    }

    message.success('字幕已删除')
}

// 导入相关方法
const importSubtitles = () => {
    importModalVisible.value = true
}

const handleFileChange = (options: any) => {
    importFile.value = options.file.file
}

const confirmImport = () => {
    if (!importFile.value) {
        message.error('请选择文件')
        return
    }

    // 这里应该有实际的字幕解析逻辑
    message.success(`已导入字幕文件: ${importFile.value.name}`)
    importModalVisible.value = false
}

// 导出字幕
const exportSubtitles = () => {
    message.success('字幕已导出')
    // 实际项目中，这里会实现字幕导出为SRT或VTT文件的逻辑
}

// 播放控制
const play = () => {
    message.success('开始播放')
}

const pause = () => {
    message.success('已暂停')
}

const stop = () => {
    currentTime.value = 0
    message.success('已停止')
}

// 保存字幕
const saveSubtitles = () => {
    message.success('字幕已保存')
}

// 返回上一页
const goBack = () => {
    router.back()
}

// 生命周期钩子
onMounted(() => {
    // 初始化
})
</script>

<style lang="scss" scoped>
.subtitle-editor-container {
    padding: 20px;
    height: 100%;
    overflow-y: auto;

    .subtitle-card {
        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;

            h1 {
                margin: 0;
                font-size: 24px;
                font-weight: 500;
            }

            .header-actions {
                display: flex;
                gap: 12px;
            }
        }
    }

    .subtitle-content {
        display: flex;
        flex-direction: column;
        gap: 16px;

        .toolbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 0;

            .time-display {
                font-family: monospace;
                font-size: 14px;
            }

            .separator {
                margin: 0 4px;
                color: var(--text-color-secondary);
            }
        }

        .video-preview {
            border: 1px solid var(--border-color);
            border-radius: 4px;
            overflow: hidden;

            .video-container {
                position: relative;

                .video-frame {
                    width: 100%;
                    display: block;
                }

                .subtitle-preview {
                    position: absolute;
                    bottom: 60px;
                    left: 0;
                    right: 0;
                    display: flex;
                    justify-content: center;

                    .subtitle-text {
                        max-width: 80%;
                        text-align: center;
                        word-wrap: break-word;
                        line-height: 1.3;
                    }
                }

                .video-progress {
                    height: 24px;
                    background-color: var(--card-color);
                    padding: 4px 8px;

                    .progress-bar {
                        height: 16px;
                        background-color: var(--body-color);
                        border-radius: 8px;
                        position: relative;
                        overflow: hidden;

                        .progress-fill {
                            height: 100%;
                            background-color: var(--primary-color);
                            position: absolute;
                            top: 0;
                            left: 0;
                        }

                        .subtitle-marker {
                            position: absolute;
                            height: 8px;
                            top: 50%;
                            transform: translateY(-50%);
                            background-color: rgba(255, 255, 0, 0.7);
                            border-radius: 4px;
                            cursor: pointer;

                            &.active {
                                background-color: rgba(255, 165, 0, 0.9);
                            }

                            &:hover {
                                height: 10px;
                            }
                        }

                        .playhead {
                            position: absolute;
                            top: 0;
                            bottom: 0;
                            width: 2px;
                            background-color: var(--error-color);
                            pointer-events: none;
                        }
                    }
                }
            }
        }

        .subtitle-list {
            border: 1px solid var(--border-color);
            border-radius: 4px;
            overflow: hidden;

            .list-header {
                display: grid;
                grid-template-columns: 180px 1fr 100px;
                background-color: var(--card-color);
                padding: 8px 12px;
                font-weight: 500;
                border-bottom: 1px solid var(--border-color);
            }

            .list-body {
                max-height: 200px;
                overflow-y: auto;

                .subtitle-item {
                    display: grid;
                    grid-template-columns: 180px 1fr 100px;
                    padding: 8px 12px;
                    border-bottom: 1px solid var(--border-color);
                    cursor: pointer;

                    &:last-child {
                        border-bottom: none;
                    }

                    &:hover {
                        background-color: var(--body-color-hover);
                    }

                    &.selected {
                        background-color: var(--primary-color-suppl);
                    }

                    .item-time {
                        font-family: monospace;
                        font-size: 14px;
                    }

                    .item-text {
                        white-space: nowrap;
                        overflow: hidden;
                        text-overflow: ellipsis;
                    }

                    .item-actions {
                        text-align: right;
                    }
                }
            }
        }

        .subtitle-editor {
            border: 1px solid var(--border-color);
            border-radius: 4px;
            padding: 16px;
        }
    }

    .upload-tip {
        font-size: 12px;
        color: var(--text-color-secondary);
        margin-top: 4px;
    }
}

/* 响应式调整 */
@media (max-width: 768px) {
    .subtitle-editor-container {
        padding: 10px;
    }
}
</style>